package com.baseweb.webadmin.controller.admin;


import com.baseweb.webadmin.alipay.config.AlipayConfig;
import com.baseweb.webadmin.alipay.util.AlipayNotify;
import com.baseweb.webadmin.alipay.util.AlipayParams;
import com.baseweb.webadmin.alipay.util.AlipaySubmit;
import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.*;
import com.baseweb.webadmin.core.model.bvo.*;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.Const;
import com.baseweb.webadmin.core.util.DateUtil;
import com.baseweb.webadmin.core.util.ObjectFormatter;
import com.baseweb.webadmin.service.*;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping(value = "/agent")
public class AgentController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(AgentController.class);

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private UserService userService;

    @Autowired
    private ContentService contentService;

    private String PREFIX = "/agent/";

    @RequestMapping(value = "/orderManage")
    public String orderManage() {
        return PREFIX + "orderManage";
    }

    @RequestMapping(value = "/getOrderList")
    public void getOrderList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        User user = getCurrentUser();
        List<ByUserOrderInfoBvo> list = new ArrayList<ByUserOrderInfoBvo>();
        int total = 0;

        List<User> userList = userService.selectAgentUserList(user.getId(), BaseState.NORMAL.getCode(), null, null, null, 0, Integer.MAX_VALUE);
        List<Integer> userIds = new ArrayList<Integer>();
        if (userList != null && userList.size() > 0){
            for (User current : userList){
                userIds.add(current.getId());
            }
        }

        if (userIds != null && userIds.size() > 0) {
            List<ByUserOrder> byUserOrders = userOrderService.selectBizOrderListByPage(userIds, OrderStatus.NEW_ORDER.getCode(), (page - 1) * pageSize, pageSize);
            if (byUserOrders != null && byUserOrders.size() > 0) {
                for (ByUserOrder current : byUserOrders) {
                    User bizUser = userService.selectUserById(current.getBizUserId());
                    list.add(ByUserOrderInfoBvo.copyFrom(current, userService.selectUserById(current.getUserId()),
                            UserInfoBvo.copyFrom(bizUser, null, contentService.findChannel(bizUser.getBizWorkType()))));
                }
            }

            total = userOrderService.selectBizOrderListCount(userIds, OrderStatus.NEW_ORDER.getCode());
        }

        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }

//    @RequestMapping(value = "/orderDetailManage")
//    public String orderDetailManage(@RequestParam(value = "order_id",required = false) Integer order_id,
//                                    Model model) {
//        model.addAttribute("order_id", order_id);
//
//        return PREFIX + "orderDetailManage";
//    }
//
//    @RequestMapping(value = "/getOrderDetailList")
//    public void getOrderDetailList(@RequestParam(value = "page", defaultValue = "1") Integer page,
//                             @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
//                             @RequestParam(value = "user_id",required = false) Integer user_id,
//                             @RequestParam(value = "order_id",required = false) Integer order_id,
//                             Model model) {
//        if (pageSize == null || pageSize == 0) {
//            pageSize = 20;
//        }
//
////        User user = getCurrentUser();
////        List<ByUserOrderDetail> list = userOrderService.selectOrderDetailListByPage(user_id, order_id, (page-1)*pageSize, pageSize);
//
//        List<ByUserOrderDetailInfoBvo> list = new ArrayList<ByUserOrderDetailInfoBvo>();
//        List<ByUserOrderDetail> byUserOrders = userOrderService.selectOrderDetailListByPage(user_id, order_id, (page-1)*pageSize, pageSize);
//        if (byUserOrders != null && byUserOrders.size()>0){
//            for(ByUserOrderDetail current : byUserOrders){
//                list.add(ByUserOrderDetailInfoBvo.copyFrom(current, userService.selectUserById(current.getUserId()),
//                        userService.selectUserById(current.getBizUserId()), userService.findBizProduct(current.getProductId())));
//            }
//        }
//
//        int total = userOrderService.selectOrderDetailListCount(user_id, order_id);
//        model.addAttribute("list", list);
//        model.addAttribute("total", total);
//        model.addAttribute("pageSize", pageSize);
//    }


    @RequestMapping(value = "/withdrawManage")
    public String withdrawManage() {
        return PREFIX + "withdrawManage";
    }

    @RequestMapping(value = "/getWithdrawList")
    public void getWithdrawList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        User user = getCurrentUser();
        List<ByUserWithdrawBvo> list = new ArrayList<ByUserWithdrawBvo>();
        int total = 0;

        List<User> userList = userService.selectAgentUserList(user.getId(), BaseState.NORMAL.getCode(), null, null, null, 0, Integer.MAX_VALUE);
        List<Integer> userIds = new ArrayList<Integer>();
        if (userList != null && userList.size() > 0){
            for (User current : userList){
                userIds.add(current.getId());
            }
        }

        if (userIds != null && userIds.size() > 0) {
            List<ByUserWithdraw> byUserWithdraws = accountService.selectWithdrawListByIdsPage(userIds, (page - 1) * pageSize, pageSize);

            for (ByUserWithdraw current : byUserWithdraws) {
                ByUserWithdrawBvo bvo = ByUserWithdrawBvo.copyFrom(current, userService.selectUserById(current.getUserId()),
                        accountService.findWithdrawAccount(current.getAccountId()));

                list.add(bvo);
            }

            total = accountService.selectWithdrawListIdsCount(userIds);
        }

        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }

    @RequestMapping(value = "/userManager", method = RequestMethod.GET)
    public String userManager(Model model) {
        model.addAttribute("roleList", getSubRoleOfCurrentUser());
        return PREFIX + "userManager";
    }

    /**
     * 展示用户
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/viewUsers")
    public void viewUsers(@RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
                          @RequestParam(value = "pageSize", defaultValue = "20", required = false) Integer pageSize,
                          @RequestParam(value = "cn_name", required = false) String cn_name,
                          @RequestParam(value = "username", required = false) String username,
                          @RequestParam(value = "identity", required = false) String identity,
                          Model model) {
        User user = getCurrentUser();

        List<User> list = userService.selectAgentUserList(user.getId(), BaseState.NORMAL.getCode(), cn_name, username, identity, (page-1)*pageSize, pageSize);
        int total = userService.selectAgentUserListCount(user.getId(), BaseState.NORMAL.getCode(), cn_name, username, identity);

        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }

    //获取当前用户所具有的子孙角色
    private List<Role> getSubRoleOfCurrentUser() {
        User user = userService.selectByName(getUserName());
        if (user == null) {
            return null;
        } else {
            List<Role> list = roleService.selectRolesByUser(user.getId()); //获取当前用户的所有角色
            List<Role> directRoleList = roleService.selectRoleListByUser(user.getId().toString()); //获取当前用户的所有直接角色

            for (Role role : directRoleList) {
                for (int i = list.size() - 1; i >= 0; i--) {
                    Role r = list.get(i);
                    if (r != null && r.getId().equals(role.getId())) {
                        list.remove(i);
                    }
                }
            }

            return list;
        }
    }

}
